Partial correlation between two variables when a correlation matrix is given.
partialcor(R, indx, indy, indz, n)
The partial correlation coefficient and the p-value for the test of zero partial correlation.
A correlation matrix.
The index of the first variable whose conditional correlation is to estimated.
The index of the second variable whose conditional correlation is to estimated.
The index of the conditioning variables.
The sample size of the data from which the correlation matrix was computed.
Michail Tsagris
R implementation and documentation: Michail Tsagris mtsagris@uoc.gr.
Suppose you want to calculate the correlation coefficient between two variables controlling for the effect of (or conditioning on) one or more other variables. So you cant to calculate \(\hat{\rho}\left(X,Y|{\bf Z}\right)\), where \(\bf Z\) is a matrix, since it does not have to be just one variable. Using the correlation matrix \(R\) we can do the following: $$ r_{X,Y|{\bf Z}}= { \begin{array}{cc} \frac{R_{X,Y} - R_{X, {\bf Z}} R_{Y,{\bf Z}}}{ \sqrt{ \left(1 - R_{X,{\bf Z}}^2\right)^T \left(1 - R_{Y,{\bf Z}}^2\right) }} & \text{if} \ \ |{\bf Z}|=1 \\ -\frac{ {\bf A}_{1,2} }{ \sqrt{{\bf A}_{1,1}{\bf A}_{2,2}} } & \text{if} \ \ |{\bf Z}| > 1 \end{array} } $$
The \(R_{X,Y}\) is the correlation between variables \(X\) and \(Y\), \(R_{X,{\bf Z}}\) and \(R_{Y,{\bf Z}}\) denote the correlations between \(X\) & \(\bf Z\) and \(Y\) & \(\bf Z\), \({\bf A}={\bf R}_{X,Y,{\bf Z}}^{-1}\), with \(\bf A\) denoting the correlation sub-matrix of variables \(X, Y, {\bf Z}\) and \(A_{i,j}\) denotes the element in the \(i\)-th row and \(j\)-th column of matrix \(A\). The \(|{\bf Z}|\) denotes the cardinality of \(\bf Z\), i.e. the number of variables.
partialcor2, pcormat
r <- cor(iris[, 1:4])
partialcor(r, 1, 2, 3:4, 150)
Run the code above in your browser using DataLab